/**
 *  jsExportExcel js导出excel文件
 */
// vuex
import store from "@/store";
// API
import { dataBoardByChartId, dataBoardMerchantGetChatData } from '@/api/dataCenter/dataBoard.js';
import { dateStrChangeTimeTamp } from './utils.js'
var reportData = [];
var payloadData = null;
var column = [];
var tableData = [];
// 获取报表数据
const dataBoardByChartIdApi = async function (id) {
  let res = await dataBoardByChartId({
    id
  });
  if(res.code === 200) {
    this.reportData = res.payload;
    // 获取Excel数据
    dataBoardMerchantGetChatDataApi(id);
  }
}
// 获取报表具体数据
const dataBoardMerchantGetChatDataApi = async function (id) {
  let startTime;
  let endTime;
  let screenTime = store.state.user.screenTime;
  if(screenTime && screenTime.length != 0) {
    startTime = dateStrChangeTimeTamp(screenTime[0]);
    endTime = dateStrChangeTimeTamp(screenTime[1]);
  } else {
    // startTime 和 endTime存在即固定时间
    if(this.reportData.startTime && this.reportData.endTime) {
      startTime = this.reportData.startTime;
      endTime = this.reportData.endTime;
    }
    // relativelyTime存在即相对时间
    if(this.reportData.relativelyTime) {
      let nowDate = new Date().getTime();
      let startDate = nowDate - this.reportData.relativelyTime;
      startTime = startDate;
      endTime = nowDate;
    }
  }
  let res = await dataBoardMerchantGetChatData({
    id,
    startTime,
    endTime,
    insId: store.state.insId.insId,
    currentPage: 1,
    showCount: 99999
  })
  if(res.code === 200) {
    this.payloadData = res.payload;
    capsulationDealData();
  }
}

// 处理数据封装
function capsulationDealData() {
  // 1、区分分组和不分组情况
  if(this.payloadData.groupColumn && this.payloadData.groupColumn.indexOf('columnHumpName') != -1) {
  // 1.1分组逻辑
    let specialColumn = [];
    let indicatorsColumn = ''; // 分组表格首个表头
    let columnHumpName = ''; // 获取数据存储字段
    let groupColumn = JSON.parse(this.payloadData.groupColumn.replace(/\\/g, ''));
    indicatorsColumn = groupColumn[0].columnDesc;
    columnHumpName = groupColumn[0].columnHumpName;

    if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) { // 多指标
      // 处理表头
      let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
      dealSpecialColumn.forEach(item => {
        let obj = {};
        obj.enVal = item.split('=')[0];
        obj.chnVal = item.split('=')[1];
        specialColumn.push(obj);
      })
      console.log(specialColumn, 'specialColumn')
      column = [
        {
          prop: 'totalColumn',
          align: '',
          label: indicatorsColumn,
          scopeStatus:false,
          width:"",
        },
        {
          align: '',
          label: '合计',
          scopeStatus:false,
          width:"",
          isNested: true,
          childrenColumn: []
        }
      ];
      // 处理合计列表头
      specialColumn.forEach(item => {
        let obj = {
          prop: '',
          align: '',
          label: '',
          scopeStatus:false,
          width:"",
        }
        obj.prop = item.enVal;
        obj.label = item.chnVal;
        column[1].childrenColumn.push(obj);
      })
      console.log('column', column);

      // 处理具体数据
      let dayData = [];
      dayData = JSON.parse(JSON.stringify(this.payloadData.dayData));
      dayData.forEach(item => {
        item.time = new Date(item.createTime).format("yyyy-MM-dd");
        item.dayData = JSON.parse(item.dayData.replace(/\\/g, ''));
      })
      console.log('dayData', dayData)
      // 提取第一列
      let tableDataStep1 = [];
      dayData.forEach((item, index) => {
        if(index === 0) {
          item.dayData.forEach(val => {
            let obj = {};
            for(let i in val) {
              if(String(columnHumpName) === String(i)) {
                obj['totalColumn'] = val[i];
              } else {
                obj[i] = 0;
              }
            }
            tableDataStep1.push(obj);
          })
        }
      })
      dayData.forEach(item => {
        item.time = new Date(item.createTime).format("yyyy-MM-dd");
        item.dayData.forEach(val1 => {
          tableDataStep1.forEach(val2 => {
            if(val1[columnHumpName] === val2.totalColumn) {
              for(let i in val1) {
                for(let j in val2) {
                  if(i === j) {
                    val2[j] += val1[i];
                  }
                }
              }
            } 
          })
        })
      })

      dayData.forEach(item => {
        item.dayData.forEach(val1 => {
          tableDataStep1.forEach(val2 => {
            if(val1[columnHumpName] === val2.totalColumn) {
              for(let i in val1) {
                for(let j in val2) {
                  if(i === j) {
                    val2[i + item.time] = val1[i];
                  }
                }
              }
            } 
          })
        })
      })
      console.log('tableDataStep1', tableDataStep1)
      tableData = tableDataStep1;

      // 处理剩余日期表头
      dayData.forEach(item => {
        let obj1 = {
          align: '',
          label: item.time,
          scopeStatus:false,
          width:"",
          isNested: true,
          childrenColumn: []
        }
        specialColumn.forEach(val1 => {
          let obj2 = {
            prop: '',
            align: '',
            label: '',
            scopeStatus:false,
            width:"",
          }
          item.dayData.forEach(val2 => {
            for(let i in val2) {
              if(i === val1.enVal) {
                obj2.prop = val1.enVal + item.time;
                obj2.label = val1.chnVal;
              }
            }
          })
          obj1.childrenColumn.push(obj2)
        })
        column.push(obj1)
      })
      console.log('column', column)
    } else { // 单指标
      // 处理表头
      specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=')[0];
      column = [
        {
          prop: columnHumpName,
          align: '',
          label: indicatorsColumn,
          scopeStatus:false,
          width:"",
        },
        {
          prop: 'totalColumn',
          align: '',
          label: '合计',
          scopeStatus:false,
          width:"",
        }
      ];
      this.payloadData.dayData.forEach(item => {
        let obj = {
          prop: new Date(item.createTime).format("yyyy-MM-dd"),
          align: '',
          label: new Date(item.createTime).format("yyyy-MM-dd"),
          scopeStatus:false,
          width:"",
        }
        column.push(obj);
      })

      // 处理数据
      let dayData = [];
      dayData = JSON.parse(JSON.stringify(this.payloadData.dayData));
      dayData.forEach(item => {
        item.time = new Date(item.createTime).format("yyyy-MM-dd");
        item.dayData = JSON.parse(item.dayData.replace(/\\/g, ''));
      })
      console.log('dayData', dayData)
      // 提取每个日期对应的数据
      let tableDataStep1 = [];
      dayData.forEach(item => {
        item.dayData.forEach(val => {
          let obj = {
            time: item.time,
          }
          for(let i in val) {
            if(String(specialColumn) === String(i)) {
              obj[i] = val[i]
            }
            if(String(columnHumpName) === String(i)) {
              obj[i] = val[i]
            }
          }
          tableDataStep1.push(obj);
        })
      })
      console.log('tableDataStep1', tableDataStep1)
      // 计算整合合计数据
      let tableDataStep2 = [];
      let arr = [];
      tableDataStep1.forEach(item => {
        for(let i in item) {
          if(String(columnHumpName) === String(i)) {
            arr.push(item[i]);
          }
        }
      })
      arr = Array.from(new Set(arr));
      console.log('arr', arr)
      arr.forEach(item => {
        let num = 0;
        tableDataStep1.forEach(val => {
          for(let i in val) {
            if(val[i] === item) {
              num += val[specialColumn]
            }
          }
        })
        let obj = {}
        obj[columnHumpName] = item;
        obj.totalColumn = num;
        tableDataStep2.push(obj);
      })
      console.log('tableDataStep2', tableDataStep2)
      // 整合统计和日期数据
      tableDataStep2.forEach(item => {
        tableDataStep1.forEach(val => {
          if(item[columnHumpName] === val[columnHumpName]) {
            item[val.time] = val[specialColumn]
          }
        })
      })
      tableData = tableDataStep2;
    }
  } else {
  // 1.2不分组逻辑
    let specialColumn = [];
    // 具体数值字段获取
    if(this.payloadData.specialColumn.indexOf(',') != -1) {
      // 多指标
      let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
      dealSpecialColumn.forEach(item => {
        let obj = {};
        obj.enVal = item.split('=')[0];
        obj.chnVal = item.split('=')[1];
        specialColumn.push(obj);
      })
      column = [
        {
          prop: 'date',
          align: '',
          label: '日期',
          scopeStatus:false,
          width:"",
        }
      ]
      specialColumn.forEach(item => {
        let obj = {
          prop: item.enVal,
          align: '',
          label: item.chnVal,
          scopeStatus:false,
          width:"",
        }
        column.push(obj);
      })
    } else {
      // 单指标
      specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=');
      column = [
        {
          prop: 'date',
          align: '',
          label: '日期',
          scopeStatus:false,
          width:"",
        }
      ];
      let obj = {
        prop: specialColumn[0],
        align: '',
        label: specialColumn[1],
        scopeStatus:false,
        width:"",
      }
      column.push(obj);
    }
    // 处理具体数据
    // Step1
    let chartData = [];
    this.payloadData.dayData.forEach(item => {
      let obj = {};
      obj.date = new Date(item.createTime).format("yyyy-MM-dd");
      obj.id = item.id
      obj.insId = item.insId
      obj.reportId = item.reportId
      obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
      let objVal = Object.assign({}, obj, obj.value[0]);
      chartData.push(objVal);
    });
    // 合计
    if(specialColumn.length <= 2) {
      // 单指标
      let totalNum = 0;
      chartData.forEach(item => {
        for(let i in item) {
          if(String(specialColumn[0]) === String(i)) {
            totalNum += item[i];
          }
        }
      })
      tableData = JSON.parse(JSON.stringify(chartData));
      tableData.unshift(chartData[chartData.length -1]);
      tableData.forEach((item, index) => {
        if(index === 0) {
          item.date = '合计'
          for(let i in item) {
            if(String(specialColumn[0]) === String(i)) {
              item[i] = totalNum;
            }
          }
        }
      })
    } else {
      // 多指标
      let totalArr = [];
      specialColumn.forEach((item, index) => {
        let totalObj = {
          num: 0,
          enVal: ''
        }
        chartData.forEach((val, key) => {
          for(let i in val) {
            if(String(item.enVal) === String(i)) {
              totalObj.enVal = item.enVal;
              totalObj.num += val[i];
            }
          }
        })
        totalArr.push(totalObj);
      })
      tableData = JSON.parse(JSON.stringify(chartData));
      tableData.unshift(chartData[chartData.length -1]);
      tableData.forEach((item, index) => {
        if(index === 0) {
          item.date = '合计'
          totalArr.forEach(val => {
            for(let i in item) {
              if(val.enVal === String(i)) {
                item[i] = val.num;
              }
            }
          })
        }
      })
    }
  }
  console.log('tableData', tableData)
  console.log('column', column)
  // 导出excel
  
}

export function jsExportJsonExcel(id) {
  dataBoardByChartIdApi(id);
}